// 获取DOM元素
const taskInput = document.getElementById('taskInput');
const addBtn = document.getElementById('addBtn');
const taskList = document.getElementById('taskList');
const totalTasksSpan = document.getElementById('totalTasks');

// 从localStorage加载任务
let tasks = JSON.parse(localStorage.getItem('tasks')) || [];

// 初始化
renderTasks();

// 添加任务
function addTask() {
    const taskText = taskInput.value.trim();
    
    if (taskText === '') {
        alert('请输入任务内容！');
        return;
    }
    
    const newTask = {
        id: Date.now(),
        text: taskText,
        completed: false,
        createdAt: new Date().toLocaleString('zh-CN')
    };
    
    tasks.unshift(newTask);
    saveTasks();
    renderTasks();
    taskInput.value = '';
    taskInput.focus();
}

// 删除任务
function deleteTask(id) {
    if (confirm('确定要删除这个任务吗？')) {
        tasks = tasks.filter(task => task.id !== id);
        saveTasks();
        renderTasks();
    }
}

// 切换任务状态
function toggleTask(id) {
    tasks = tasks.map(task => 
        task.id === id ? { ...task, completed: !task.completed } : task
    );
    saveTasks();
    renderTasks();
}

// 保存到localStorage
function saveTasks() {
    localStorage.setItem('tasks', JSON.stringify(tasks));
}

// 渲染任务列表
function renderTasks() {
    if (tasks.length === 0) {
        taskList.innerHTML = '<p class="empty-message">暂无任务，快来添加第一个任务吧！</p>';
    } else {
        taskList.innerHTML = tasks.map(task => `
            <div class="task-item ${task.completed ? 'completed' : ''}">
                <input type="checkbox" 
                       class="task-checkbox" 
                       ${task.completed ? 'checked' : ''}
                       onchange="toggleTask(${task.id})">
                <span class="task-text">${escapeHtml(task.text)}</span>
                <button class="delete-btn" onclick="deleteTask(${task.id})">删除</button>
            </div>
        `).join('');
    }
    
    // 更新统计信息
    totalTasksSpan.textContent = `总计：${tasks.length} 个任务`;
}

// HTML转义，防止XSS攻击
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 监听回车键
taskInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        addTask();
    }
});

// 防止按钮连续点击
addBtn.addEventListener('click', function() {
    addTask();
});

// 页面加载时聚焦输入框
window.addEventListener('load', function() {
    taskInput.focus();
});
